package com.pachong.android.baseuicomponent.refreshable.pullrefresh;

import android.content.Context;
import android.view.View;

import com.pachong.android.baseuicomponent.refreshable.IRefreshable;
import com.pachong.android.baseuicomponent.refreshable.OnRefreshListener;


/**
 * Pullable refresh view helper
 *
 * @author Vivi Peng
 * @version 1.0.0
 * @e-mail pengveivei@sina.cn
 * @QQ 897058316
 * @since 16/2/1
 */
public class PullableRefreshViewHelper implements IRefreshable {

    private Context mContext;
    private Object mComponent;
    private PullToRefreshLayout mRefreshLayout;
    private OnRefreshListener mRefreshListener = null;

    public PullableRefreshViewHelper(Context context, Object component) {
        mContext = context;
        mComponent = component;
    }


    /**
     * 这里不要调用Component的onStartRefreshing,会出现无限的递归调用
     */
    @Override
    public void onStartRefreshing() {

    }

    /**
     * 隐藏刷新控件
     */
    public void hideRefreshView() {
        if (null != mRefreshLayout) {
            mRefreshLayout.refreshFinish();
        }
    }


    /**
     * 显示刷新控件
     */
    public void showRefreshView() {
        if (null != mRefreshLayout) {
//            mRefreshLayout.autoRefresh();
        }
    }


    /**
     * 设置是否需要下拉刷新的功能
     *
     * @param enable
     */
    public void setPullToRefreshEnable(boolean enable) {
        if (mRefreshLayout != null) {
            mRefreshLayout.setRefreshEnabled(enable);
        }
    }

    /**
     * 设置向下滑动刷新的listener
     * user一般不需要设置这个东西，回调onStartRefreshing足够了。
     *
     * @param listener
     */
    public void setOnRefreshListener(final OnRefreshListener listener) {
        mRefreshListener = listener;
        if (mRefreshLayout != null) {
            mRefreshLayout.setOnRefreshListener(new PullToRefreshLayout.OnRefreshListener() {

                @Override
                public void onRefresh(final PullToRefreshLayout pullToRefreshLayout) {
                    listener.onRefresh();
                }
            });
        } else {
            mRefreshLayout.setOnRefreshListener(null);
        }

    }


    public void initRefreshView(View refreshView, final IRefreshable refreshable) {
        if (refreshView != null && refreshView instanceof PullToRefreshLayout) {
            mRefreshLayout = (PullToRefreshLayout) refreshView;
            setOnRefreshListener(new OnRefreshListener() {

                @Override
                public void onRefresh() {
                    refreshable.onStartRefreshing();
                }
            });

        }
    }

}
